const express = require('express');
const router = express.Router();
const Department = require('../mysql/collection/Department');

/**
 * @api {post} /admin/department/create 创建部门
 * @apiName CreateDepartment
 * @apiGroup 管理系统-Department
 * @apiHeader {String} token  token
 * @apiParam {String} parentId 父部门ID
 * @apiParam {String} name 部门名称
 * @apiParam {String} code 部门编号
 * @apiParam {Number} sort 排序号
 * @apiParam {Number} status 状态(1启用 0禁用)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '201',
 *    message: '部门创建成功',
 *    data: {部门对象}
 *  }
 */
router.post('/create', async (req, res) => {
  try {
    const { parentId, name, code, sort, status } = req.body;
    
    // 检查部门编号是否已存在
    const existingDept = await Department.findOne({ code });
    if (existingDept) {
      return res.status(400).json({ message: '部门编号已存在' });
    }
    
    const department = new Department({ parentId, name, code, sort, status });
    await department.save();
    
    res.status(201).json({ message: '部门创建成功', data: department });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @api {get} /admin/department/list 获取部门列表
 * @apiName GetDepartmentList
 * @apiGroup 管理系统-Department
 * @apiHeader {String} token  token
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    data: [部门列表]
 *  }
 */
router.get('/list', async (req, res) => {
  try {
    const departments = await Department.find()
    .populate('parentId');
    // console.log(departments);
    
    const treeData = await Department.buildTree(departments);
    // console.log(treeData); // 打印生成的树结构，用于调试
    res.json({ data: treeData });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @api {put} /admin/department/update/:id 更新部门
 * @apiName UpdateDepartment
 * @apiGroup 管理系统-Department
 * @apiHeader {String} token  token
 * @apiParam {String} id 部门ID
 * @apiParam {String} parentId 父部门ID
 * @apiParam {String} name 部门名称
 * @apiParam {String} code 部门编号
 * @apiParam {Number} sort 排序号
 * @apiParam {Number} status 状态(1启用 0禁用)
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '部门更新成功',
 *    data: {部门对象}
 *  }
 */
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { parentId, name, code, sort, status } = req.body;
    
    // 检查部门编号是否已被其他部门使用
    const existingDept = await Department.findOne({ code, _id: { $ne: id } });
    if (existingDept) {
      return res.status(400).json({ message: '部门编号已被其他部门使用' });
    }
    
    const updatedDept = await Department.findByIdAndUpdate(
      id,
      { parentId, name, code, sort, status },
      { new: true }
    );
    
    if (!updatedDept) {
      return res.status(404).json({ message: '部门不存在' });
    }
    
    res.json({ message: '部门更新成功', data: updatedDept });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

/**
 * @api {delete} /admin/department/delete/:id 删除部门
 * @apiName DeleteDepartment
 * @apiGroup 管理系统-Department
 * @apiHeader {String} token  token
 * @apiParam {String} id 部门ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '部门删除成功',
 *    data: {部门对象}
 *  }
 */
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const deletedDept = await Department.findByIdAndDelete(id);
    
    
    if (!deletedDept) {
      return res.status(404).json({ message: '部门不存在' });
    }
    // 同时删除该部门下的所有子部门
    await Department.deleteMany({ parentId: id });
    
    res.json({ message: '部门删除成功', data: deletedDept });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;